package com.shop.shoppingmall.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.shoppingmall.dao.ShProductDao;
import com.shop.shoppingmall.dao.ShUserDao;
import com.shop.shoppingmall.entity.ShProduct;
import com.shop.shoppingmall.entity.ShProductSpecs;
import com.shop.shoppingmall.entity.ShUser;
import com.shop.shoppingmall.entity.ShopSpecs;
import com.shop.shoppingmall.service.ShProductService;
import com.shop.shoppingmall.util.*;
import com.shop.shoppingmall.util.api.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * (ShProduct)表控制层
 *
 * @author makejava
 * @since 2020-09-07 17:09:21
 */
@RestController
@RequestMapping("shProduct")
@CrossOrigin
@Slf4j
public class ShProductController extends CrossOriginFilter {
    /**
     * 服务对象
     */
    @Resource
    private ShProductService shProductService;
    @Resource
    private ShUserDao shUserDao;
    @Resource
    private ShProductDao shProductDao;
    /**
     * 发布商品及规格
     * @param jsonRequest
     * @return
     */
    @PostMapping("insert")
    public Result insert(@RequestBody String jsonRequest) {
        JSONObject jsonObject = JSONObject.parseObject(jsonRequest);
        Map<String, Object> map =jsonObject;
        String  shProduct1 = map.get("shProduct").toString();
        String shProductSpecs1 =map.get("shProductSpecs").toString();
        String  attributeList =  map.get("attributeList").toString();
        System.out.println(shProductSpecs1);
        System.out.println(attributeList);
        List<ShProduct> shProduct = JSONObject.parseArray(shProduct1,ShProduct.class);
        if(shProduct.size() == 0){
            return Result.error("商品信息不能为空");
        }
        List<ShProductSpecs> shProductSpecs = JSONObject.parseArray(shProductSpecs1,ShProductSpecs.class);
        if(shProductSpecs.size() == 0){
            return Result.error("商品细规格信息不能为空");
        }
        List<ShopSpecs> shopSpecs = JSONObject.parseArray(attributeList, ShopSpecs.class);
        if(shopSpecs.size() == 0){
            return Result.error("商品规格信息不能为空");
        }
        return shProductService.insert(shProduct,shProductSpecs,shopSpecs);
    }

    @PostMapping("qqqqq")
    public Result aaa(@RequestBody String json ) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        Map<String, Object> map =jsonObject;
        String  shProduct1 =  map.get("attributeList").toString();
        String  specs =  map.get("shProductSpecs").toString();
        List<ShProductSpecs> shProductSpecs = JSONObject.parseArray(specs,ShProductSpecs.class);
        for(ShProductSpecs productSpecs : shProductSpecs){
            String ww =  productSpecs.getPrices();
            JSONObject jsons =  JSONObject.parseObject(ww);
            Integer productStock = Integer.valueOf(jsons.getString("productStock"));
            String photo =  jsons.getString("photo");
            String productPrice =  jsons.getString("productPrice");
            productSpecs.setProductStock(productStock);
            productSpecs.setPhoto(photo);
            productSpecs.setProductPrice(new BigDecimal(productPrice));
        }
        List<ShopSpecs> shopSpecs = JSONObject.parseArray(shProduct1, ShopSpecs.class);
        String xx = "";
        for(ShopSpecs shopSpecs1 : shopSpecs){
            String a =  shopSpecs1.getChildren();
            String b= shopSpecs1.getType();
            xx = xx+","+ '"'+b +'"'+":"+a;
        }
        String str1=xx.substring(0, xx.indexOf(","));
        String str2=xx.substring(str1.length()+1, xx.length());
        System.out.println('{'+str2+'}');
        return Result.ok(str2);
    }

    /**
     * 根据商户id查询该商户发布的所有商品
     * @param businessId
     * @param page
     * @return
     */
    @GetMapping("selectAllProduct/{page}")
    public Result selectAllProduct(@RequestParam("businessId") String businessId ,@PathVariable Integer page){
        return shProductService.selectAllProduct(businessId,page);
    }

    /**
     * 根据商品id查询该商品详细信息
     * @param productId
     * @return
     */
    @GetMapping("selectProductById1")
    public Result selectProductById1(@RequestParam("productId") String productId, HttpServletRequest request){
        return shProductService.selectProductById1(productId,request);
    }

    /**
     * 后台根据商品id查询商品详细信息
     * @param map
     * @return
     */
    @PostMapping("selectProduct")
    public Result selectProduct(@RequestBody Map map){
        System.out.println(map);
      String productId =  map.get("productId").toString();
        System.out.println(productId+"===================");
        return shProductService.selectProduct(productId);
    }

    /**
     * 添加商品新规格
     * @param jsonRequest
     * @return
     */
    @PostMapping("insertSpecs")
    public Result insertSpecs(@RequestBody String jsonRequest) {
        JSONObject jsonObject = JSONObject.parseObject(jsonRequest);
        Map<String, Object> map =jsonObject;
        String  shProduct1 = map.get("shProduct").toString();
        String shProductSpecs1 =map.get("shProductSpecs").toString();
        String  attributeList =  map.get("attributeList").toString();
        System.out.println(shProductSpecs1);
        System.out.println(attributeList);
        List<ShProductSpecs> shProductSpecs = JSONObject.parseArray(shProductSpecs1,ShProductSpecs.class);
        if(shProductSpecs.size() == 0){
            return Result.error("商品细规格信息不能为空");
        }
        List<ShopSpecs> shopSpecs = JSONObject.parseArray(attributeList, ShopSpecs.class);
        if(shopSpecs.size() == 0){
            return Result.error("商品规格信息不能为空");
        }
        return shProductService.insertSpecs(shProduct1,shProductSpecs,shopSpecs);
    }

    /**
     * 根据商品id和对应规格查询商品价格和库存情况
     * @param productId 商品id
     * @param productSpecs  规格
     * @return
     */
    @PostMapping("selectSpecs")
    public Result selectSpecs(String productId,String productSpecs){
        return shProductService.selectSpecs(productId,productSpecs);
    }

    /**
     * 根据各级分类id查询该分类下的所有商品
     * @param map
     * @return
     */
    @PostMapping("listAll")
    public Result listAll(@RequestBody Map map){
        System.out.println(map);
        return shProductService.listAll(map);
    }

    /**
     * 后台查询商品列表
     * @param map
     * @return
     */
    @PostMapping("selectList")
    public Result selectlist(@RequestBody Map map){
        System.out.println(map);
        return shProductService.queryList(map);
    }
    /**
     *
     * 商品查询
     * type=1折扣最高,3新品上架按时间排序,4爆品抢购
     * @param
     * @return
     */
    @PostMapping("selectByList")
    public Result selectByList(@RequestBody Map map){
        List<ShProduct> shProductList =  shProductDao.selectByList(map);
       //封装分页数据
        return shProductService.selectByList(map);
    }



    /**
     * 图片上传接口
     * @param imgFile
     * @return
     * @throws IOException
     */
    @GetMapping("memoryPhoto")
    public Result memoryPhoto(MultipartFile imgFile) throws IOException {
        String photo =  PhotoUtil.memoryPhoto(imgFile);
        return Result.ok(photo);
    }

    /**
     * 发布商品时上传的视频和图片接口
     * @param imgFile
     * @return
     * @throws Exception
     */
    @PostMapping("/moreFileUpload")
    public Result testUpload(MultipartHttpServletRequest imgFile) throws Exception {
        Iterator<String> fileNames = imgFile.getFileNames();
        while (fileNames.hasNext()) {
            //把fileNames集合中的值打出来
            String fileName=fileNames.next();
            List<MultipartFile> fileList=imgFile.getFiles(fileName);
            if (fileList.size()>0) {
                //遍历文件列表
                Iterator<MultipartFile> fileIte=fileList.iterator();
                String newName="";
                String oldName="";
                List<String> name = new ArrayList<>();
                while (fileIte.hasNext()) {
                    //获得每一个文件
                    MultipartFile file =fileIte.next();
                    /*上传*/
                    String filePath = ""; //映射的地址
                    InputStream input = file.getInputStream();
                    oldName = file.getOriginalFilename();//获取file图片名称
                    int index = oldName.lastIndexOf(".");//找到 . 的位置
                    String suffix = oldName.substring(index);//根据 . 的位置进行分割，拿到文件后缀名
                    newName = UUID.randomUUID().toString() + suffix;//uuid生成新的文件名
                    boolean result = FtpU.uploadFile("47.105.157.251", 22, "root", "Sdxz1234", "/usr/local/etc/images", filePath, newName, input);
                    name.add(newName);
                    System.out.println(newName);
                    System.out.println(result);
                }
                return Result.ok(name);
            }
        }
        return Result.error("数据异常");
    }

    /**
     * 上传单张图片借口
     * @param imgFile
     * @return
     * @throws Exception
     */
    @PostMapping("/FileUpload")
    public Result Upload(MultipartHttpServletRequest imgFile) throws Exception {
        Iterator<String> fileNames = imgFile.getFileNames();
        while (fileNames.hasNext()) {
            //把fileNames集合中的值打出来
            String fileName=fileNames.next();
            List<MultipartFile> fileList=imgFile.getFiles(fileName);
            if (fileList.size()>0) {
                //遍历文件列表
                Iterator<MultipartFile> fileIte=fileList.iterator();
                String newName="";
                String oldName="";
                while (fileIte.hasNext()) {
                    //获得每一个文件
                    MultipartFile file =fileIte.next();
                    /*上传*/
                    String filePath = ""; //映射的地址
                    InputStream input = file.getInputStream();
                    oldName = file.getOriginalFilename();//获取file图片名称
                    int index = oldName.lastIndexOf(".");//找到 . 的位置
                    String suffix = oldName.substring(index);//根据 . 的位置进行分割，拿到文件后缀名
                    newName = UUID.randomUUID().toString() + suffix;//uuid生成新的文件名
                    boolean result = FtpU.uploadFile("47.105.157.251", 22, "root", "Sdxz1234", "/usr/local/etc/images", filePath, newName, input);
                    System.out.println(newName);
                    System.out.println(result);
                }
                return Result.ok(newName);
            }
        }
        return Result.error("数据异常");
    }

    @GetMapping("findCourier")
    public Result findCourier(String courierNum) {
        return shProductService.findCourier(courierNum);
    }

    @PostMapping("findCourier")
    public Result cartes(@RequestBody Map map) {
        List<String> listSub1= (List<String>) map.get("listSub1");
        List<String> listSub2= (List<String>) map.get("listSub2");
        return shProductService.cartes(listSub1,listSub2);
    }



    /**
     * 查询店铺详细信息
     * @param businessId
     * @param request
     * @return
     */
    @GetMapping("queryByBusId")
    public Result queryByBusId(String businessId,HttpServletRequest request) {
        String name = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(name);
        if(shUser == null || name == null){
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        return shProductService.queryByBusId(businessId,shUser.getId());
    }

    /**
     * 修改商品信息
     * @param shProduct
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody ShProduct shProduct){
        return shProductService.update(shProduct);
    }

    @PostMapping("/selectByBusId")
    public Result selectByBusId(HttpServletRequest request){
        return shProductService.selectByBusId(request);
    }

    /**
     * 随机获取6条商品信息
     * @return
     */
    @GetMapping("/selectRandProduct")
    public Result selectRandProduct(){
        return shProductService.selectRandProduct();
    }

}
